package com.castle.fortress.admin.study.exam.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

import com.castle.fortress.admin.study.exam.dto.*;
import com.castle.fortress.admin.study.exam.entity.StudyExamStatisticsEntity;
import com.castle.fortress.admin.study.exam.entity.StudyExamStatisticsMemberEntity;
import com.castle.fortress.admin.study.exam.entity.StudyMemberExamEntity;
import com.castle.fortress.admin.study.exam.mapper.StudyExamStatisticsMemberMapper;
import com.castle.fortress.admin.study.exam.service.*;
import com.castle.fortress.common.enums.YesNoEnum;
import com.castle.fortress.common.utils.ConvertUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.castle.fortress.admin.study.exam.entity.StudyMemberUnfinishExamEntity;
import com.castle.fortress.admin.study.exam.mapper.StudyMemberUnfinishExamMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * 会员未完成试卷信息 服务实现类
 *
 * @author castle
 * @since 2023-02-16
 */
@Service
public class StudyMemberUnfinishExamServiceImpl extends ServiceImpl<StudyMemberUnfinishExamMapper, StudyMemberUnfinishExamEntity> implements StudyMemberUnfinishExamService {
    @Autowired
    private StudyExamService studyExamService;
    @Autowired
    private StudyExamStatisticsMemberMapper studyExamStatisticsMemberMapper;
    @Autowired
    private StudyMemberExamService studyMemberExamService;
    @Autowired
    private StudyExamStatisticsService studyExamStatisticsService;

    /**
    * 获取查询条件
    * @param studyMemberUnfinishExamDto
    * @return
    */
    public QueryWrapper<StudyMemberUnfinishExamEntity> getWrapper(StudyMemberUnfinishExamDto studyMemberUnfinishExamDto){
        QueryWrapper<StudyMemberUnfinishExamEntity> wrapper= new QueryWrapper();
        if(studyMemberUnfinishExamDto != null){
            StudyMemberUnfinishExamEntity studyMemberUnfinishExamEntity = ConvertUtil.transformObj(studyMemberUnfinishExamDto,StudyMemberUnfinishExamEntity.class);
            wrapper.eq(studyMemberUnfinishExamEntity.getId() != null,"id",studyMemberUnfinishExamEntity.getId());
            wrapper.eq(studyMemberUnfinishExamEntity.getExamId() != null,"exam_id",studyMemberUnfinishExamEntity.getExamId());
            wrapper.eq(studyMemberUnfinishExamEntity.getMemberId() != null,"member_id",studyMemberUnfinishExamEntity.getMemberId());
            wrapper.eq(studyMemberUnfinishExamEntity.getExamTime() != null,"exam_time",studyMemberUnfinishExamEntity.getExamTime());
            wrapper.eq(studyMemberUnfinishExamEntity.getExamQuestionId() != null,"exam_question_id",studyMemberUnfinishExamEntity.getExamQuestionId());
            wrapper.eq(StrUtil.isNotEmpty(studyMemberUnfinishExamEntity.getQuestionType()),"question_type",studyMemberUnfinishExamEntity.getQuestionType());
            wrapper.eq(studyMemberUnfinishExamEntity.getScore() != null,"score",studyMemberUnfinishExamEntity.getScore());
            wrapper.like(StrUtil.isNotEmpty(studyMemberUnfinishExamEntity.getTitle()),"title",studyMemberUnfinishExamEntity.getTitle());
            wrapper.like(StrUtil.isNotEmpty(studyMemberUnfinishExamEntity.getTitleImg()),"title_img",studyMemberUnfinishExamEntity.getTitleImg());
            wrapper.like(StrUtil.isNotEmpty(studyMemberUnfinishExamEntity.getTitleMp3()),"title_mp3",studyMemberUnfinishExamEntity.getTitleMp3());
            wrapper.like(StrUtil.isNotEmpty(studyMemberUnfinishExamEntity.getOptionType()),"option_type",studyMemberUnfinishExamEntity.getOptionType());
            wrapper.like(StrUtil.isNotEmpty(studyMemberUnfinishExamEntity.getAnalysis()),"analysis",studyMemberUnfinishExamEntity.getAnalysis());
            wrapper.eq(studyMemberUnfinishExamEntity.getSort() != null,"sort",studyMemberUnfinishExamEntity.getSort());
            wrapper.like(StrUtil.isNotEmpty(studyMemberUnfinishExamEntity.getAnswer()),"answer",studyMemberUnfinishExamEntity.getAnswer());
            wrapper.like(StrUtil.isNotEmpty(studyMemberUnfinishExamEntity.getAnswerA()),"answer_a",studyMemberUnfinishExamEntity.getAnswerA());
            wrapper.like(StrUtil.isNotEmpty(studyMemberUnfinishExamEntity.getAnswerB()),"answer_b",studyMemberUnfinishExamEntity.getAnswerB());
            wrapper.like(StrUtil.isNotEmpty(studyMemberUnfinishExamEntity.getAnswerC()),"answer_c",studyMemberUnfinishExamEntity.getAnswerC());
            wrapper.like(StrUtil.isNotEmpty(studyMemberUnfinishExamEntity.getAnswerD()),"answer_d",studyMemberUnfinishExamEntity.getAnswerD());
            wrapper.like(StrUtil.isNotEmpty(studyMemberUnfinishExamEntity.getAnswerE()),"answer_e",studyMemberUnfinishExamEntity.getAnswerE());
            wrapper.like(StrUtil.isNotEmpty(studyMemberUnfinishExamEntity.getAnswerF()),"answer_f",studyMemberUnfinishExamEntity.getAnswerF());
            wrapper.like(StrUtil.isNotEmpty(studyMemberUnfinishExamEntity.getChoiceAnswer()),"choice_answer",studyMemberUnfinishExamEntity.getChoiceAnswer());
        }
        return wrapper;
    }


    @Override
    public IPage<StudyMemberUnfinishExamDto> pageStudyMemberUnfinishExam(Page<StudyMemberUnfinishExamDto> page, StudyMemberUnfinishExamDto studyMemberUnfinishExamDto) {
        QueryWrapper<StudyMemberUnfinishExamEntity> wrapper = getWrapper(studyMemberUnfinishExamDto);
        Page<StudyMemberUnfinishExamEntity> pageEntity = new Page(page.getCurrent(), page.getSize());
        Page<StudyMemberUnfinishExamEntity> studyMemberUnfinishExamPage=baseMapper.selectPage(pageEntity,wrapper);
        Page<StudyMemberUnfinishExamDto> pageDto = new Page(studyMemberUnfinishExamPage.getCurrent(), studyMemberUnfinishExamPage.getSize(),studyMemberUnfinishExamPage.getTotal());
        pageDto.setRecords(ConvertUtil.transformObjList(studyMemberUnfinishExamPage.getRecords(),StudyMemberUnfinishExamDto.class));
        return pageDto;
    }


    @Override
    public List<StudyMemberUnfinishExamDto> listStudyMemberUnfinishExam(StudyMemberUnfinishExamDto studyMemberUnfinishExamDto){
        QueryWrapper<StudyMemberUnfinishExamEntity> wrapper = getWrapper(studyMemberUnfinishExamDto);
        List<StudyMemberUnfinishExamEntity> list = baseMapper.selectList(wrapper);
        return ConvertUtil.transformObjList(list,StudyMemberUnfinishExamDto.class);
    }

    @Override
    public Boolean commitUnfinishExam(StudyMemberUnfinishExamDto examDTO) {
        QueryWrapper<StudyMemberUnfinishExamEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("exam_id",examDTO.getExamId());
        wrapper.eq("member_id",examDTO.getMemberId());
        List<StudyMemberUnfinishExamDto> examDTOS=ConvertUtil.transformObjList(list(wrapper),StudyMemberUnfinishExamDto.class);
        StudyMemberUnfinishExamDto unfinishExamDTO = examDTOS.get(0);
        StudyExamDto dto=studyExamService.getByIdExtends(examDTO.getExamId());
        StudyExamStatisticsMemberDto statisticsMemberDto = new StudyExamStatisticsMemberDto();
        statisticsMemberDto.setTimeConsuming(Integer.parseInt(String.valueOf(DateUtil.between(new Date(), unfinishExamDTO.getCreateTime(), DateUnit.SECOND))));
        statisticsMemberDto.setExamId(examDTO.getExamId());
        statisticsMemberDto.setExamName(dto.getExamName());
        List<StudyMemberExamDto> memberExamDtos=new ArrayList<>();
        for(StudyMemberUnfinishExamDto unfinish:examDTOS){
            StudyMemberExamDto memberExamDTO = new StudyMemberExamDto();
            BeanUtils.copyProperties(unfinish, memberExamDTO);
            memberExamDtos.add(memberExamDTO);
        }
        statisticsMemberDto.setExamQuestionDTOList(memberExamDtos);
        //提交未完成逻辑
        statisticsMemberDto.setMemberId(examDTO.getMemberId());
        Integer totalScore=0;
        for(StudyMemberExamDto memberExamDTO:memberExamDtos){
            if(memberExamDTO.getAnswer().equals(memberExamDTO.getChoiceAnswer())){
                totalScore+=memberExamDTO.getScore();
            }
        }
        statisticsMemberDto.setScore(totalScore);
        statisticsMemberDto.setQuizTime(new Date());
        if(totalScore>= dto.getQualifiedScore()){
            statisticsMemberDto.setStatus(YesNoEnum.YES.getCode());
        }else{
            statisticsMemberDto.setStatus(YesNoEnum.NO.getCode());
        }
        studyExamStatisticsMemberMapper.insert(ConvertUtil.transformObj(statisticsMemberDto,StudyExamStatisticsMemberEntity.class));
        for(int i=0;i<memberExamDtos.size();i++){
            memberExamDtos.get(i).setId(null);
            memberExamDtos.get(i).setRecordId(statisticsMemberDto.getId());
            memberExamDtos.get(i).setMemberId(examDTO.getMemberId());
            memberExamDtos.get(i).setSort(i+1);
        }
        List<StudyMemberExamEntity> memberExamEntities= ConvertUtil.transformObjList(memberExamDtos,StudyMemberExamEntity.class);
        studyMemberExamService.saveBatch(memberExamEntities);
        StudyExamStatisticsDto statisticsDTO =studyExamStatisticsService.queryByMemberAndExam(examDTO.getMemberId(),statisticsMemberDto.getExamId());
        //第一次考试
        if(statisticsDTO ==null){
            statisticsDTO=new StudyExamStatisticsDto();
            statisticsDTO.setExamId(statisticsMemberDto.getExamId());
            statisticsDTO.setMemberId(examDTO.getMemberId());
            statisticsDTO.setRecordId(statisticsMemberDto.getId());
            statisticsDTO.setTimeConsuming(statisticsMemberDto.getTimeConsuming());
            statisticsDTO.setQuizTime(statisticsMemberDto.getQuizTime());
            statisticsDTO.setHighScore(totalScore);
            statisticsDTO.setExamNum(1);
            statisticsDTO.setStatus(statisticsMemberDto.getStatus());
            studyExamStatisticsService.save(ConvertUtil.transformObj(statisticsDTO, StudyExamStatisticsEntity.class));
        }else{
            if(statisticsDTO.getHighScore()<=totalScore){
                statisticsDTO.setTimeConsuming(statisticsMemberDto.getTimeConsuming());
                statisticsDTO.setQuizTime(statisticsMemberDto.getQuizTime());
                statisticsDTO.setHighScore(totalScore);
                statisticsDTO.setRecordId(statisticsMemberDto.getId());
            }
            statisticsDTO.setExamNum(statisticsDTO.getExamNum()+1);
            studyExamStatisticsService.updateById(ConvertUtil.transformObj(statisticsDTO, StudyExamStatisticsEntity.class));
        }
        deleteExam(statisticsDTO.getExamId(),statisticsDTO.getMemberId());
        //校验是否有考试次数
        if(YesNoEnum.YES.getCode() == dto.getIsLimited()){
            if(statisticsDTO.getExamNum()<dto.getExamNum()){
                return true;
            }else{
                return false;
            }
        }else{
            return true;
        }
    }

    @Override
    public void deleteExam(Long examId, Long memberId) {
        QueryWrapper<StudyMemberUnfinishExamEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("exam_id",examId);
        wrapper.eq("member_id",memberId);
        baseMapper.delete(wrapper);
    }

    @Override
    public void updateOneQuestion(StudyMemberUnfinishExamDto examDTO) {
        baseMapper.updateOneQuestion(examDTO);
    }
}

